package com.atwisdom.star.config;

import com.alibaba.fastjson.JSON;
import com.atwisdom.star.respvo.UserAccountVo;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Component
@Slf4j
public class StarMetaObjectConfig implements MetaObjectHandler {

    @Autowired
    HttpServletRequest request;

    /**
     * @Description: insertFill 插入填充
     * @Param: * @param metaObject
     * @return: void
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Object loginUser;
        try{
            loginUser = request.getAttribute("loginUser");
        }catch (IllegalStateException e){
//            log.error("使用request报错, e : {}", JSON.toJSONString(e));
            loginUser = null;
        }
        if (loginUser != null) {
            UserAccountVo userAccount = (UserAccountVo) request.getAttribute("loginUser");
            this.strictInsertFill(metaObject, "createdBy", String.class, userAccount.getAccount());
        }

        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "deleteFlag", Integer.class, 0);
    }

    /**
     * @Description: updateFill 更新填充
     * @Param: * @param metaObject
     * @return: void
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        UserAccountVo userAccount;
        try{
            userAccount = (UserAccountVo) request.getAttribute("loginUser");
        }catch (IllegalStateException e){
//            log.error("使用request报错, e : {}", JSON.toJSONString(e));
            userAccount = null;
        }
        if (userAccount != null) {
            this.strictUpdateFill(metaObject, "updatedBy", String.class, userAccount.getAccount());
        }
//       this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        //解决mybatisplus的bug
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
    }
}
